package com.study.springsecurity.security.provider;


import com.study.springsecurity.security.user.DBUserDetailsManager;
import com.study.springsecurity.security.user.MyUserDetail;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class JwtTokenProvider implements AuthenticationProvider {
    @Resource
    private DBUserDetailsManager userDetailsService;
    @Resource
    private  PasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        System.out.println("JwtTokenProvider");
        String username = authentication.getName();
        String password = (String) authentication.getCredentials();

        MyUserDetail user = (MyUserDetail) userDetailsService.loadUserByUsername(username);
        if (user != null && passwordEncoder.matches(password, user.getPassword())) {
            return new UsernamePasswordAuthenticationToken(user, password, user.getAuthorities());
        }
        log.warn("密码错误");
        throw new BadCredentialsException("Invalid username or password");

    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }

}